<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <page-tools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工table -->
      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="employeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <!-- 作用插槽 头像模块 -->
              <img
                v-imgerror="defaultImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                width="80px"
                height="80px"
                @click="showCode(row.staffPhoto)"
              >
              <!-- {{ row.staffPhoto }} -->
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ formatEntry(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">

            <template #default="{ row }">
              <el-button v-if="checkButton('POINT_USER_LOOK')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button v-if="checkButton('POINT_USER_DELETE')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

    </div>
    <!-- 新增员工组件 -->
    <add-employee
      :show-dialog.sync="showDialog"
    />
    <!-- 二维码弹层 -->
    <el-dialog
      title="二维码预览图片"
      width="300px"
      :visible.sync="showCodeDialog"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 分配角色组件 -->

    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import defaultImg from '@/assets/common/head.jpg'
import dayjs from 'dayjs'
// 导入二维码文件
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employess',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      employeeList: [],
      page: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false, // 新增员工弹出层
      defaultImg, // 默认图像
      showCodeDialog: false, // 二维码的弹出层
      showRoleDialog: false, // 角色弹出层
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 员工按钮的操作权
    checkButton(type) {
      const points = this.$store.state.user.userInfo.roles.points
      return points.includes(type)
    },
    // 获取员工的综合列表数据--分页
    async getEmployeeList() {
      this.load = true
      const { data: { total, rows }} = await reqGetEmployeeList(this.page, this.pageSize)
      // console.log(res)
      this.total = total
      this.employeeList = rows
      this.loading = false
    },
    // 当前页更新
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    // 修改了每页条数后, 会造成页数的变化, 推荐从第一页重新开始展示
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新每页条数
      this.pagesize = val
      // 重置当前页
      this.page = 1
      // 调用方法, 重新请求
      this.getEmployeeList()
    },
    // 格式化聘用形式数据
    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      //  1:正式   2.非正式
      // return cellValue === 1 ? '正式' : '非正式'

      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)

      return obj ? obj.value : '未知'
    },
    formatEntry(time) {
      // 借助第三方的包dayjs或moment.js
      // return time
      return dayjs(time).format('YYYY年MM月DD')
    },
    // 删除员工
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    // 处理导出
    async handleExport() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const multiHeader = ['姓名', '主要信息', '', '', '', '', '部门']
      const headerRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出的是全部的数据
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // console.log(rows)
      // 已有的数据:[{id:xxx,mobile:xxx,username:xxx,,,,}]
      // 要的数据[[管理员,1213]]
      const arr = [] // 外层的
      rows.forEach(item => {
        const newArr = []
        headersArr.forEach(v => {
          const enkey = headerRelations[v]
          // 判断
          if (enkey === 'formOfEmployment') {
            // item[enkey] ===1  =>正式
            const obj = EmployeeEnum.hireType.find(value => value.id === +item[enkey])
            const res = obj ? obj.value : '未知'
            newArr.push(res)
          } else {
            newArr.push(item[enkey])
          }
        })
        arr.push(newArr)
      })
      // 按需加载资源
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_execl({
          header: headersArr, // 表格的头部
          data: arr,
          filename: '信息表', // 导出的excel文件名
          autoWidth: true, // 是否开启单元格宽度自适应
          bookType: 'xlsx', // 类型
          multiHeader,
          merges
        })
      })
    },
    // 控制二维码
    showCode(url) {
      if (url === '') return // 有图片才显示弹层
      this.showCodeDialog = true
      // 报错是没有获取到canvas DOM元素
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 显示员工的角色
    assignRole(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
